import { Applet } from "@/api/interface/iot";
import { ColumnProps } from "@/components/ProTable/interface";
import UploadImg from "@/components/Upload/Img.vue";
import { useApplet } from "@/hooks/useApplet";
import { filePrefix } from "@/hooks/useSystem";
import { Dict, DictType, getDictList } from "@/utils/cacheUtil";
import { AuthBtns } from "@/utils/constants";
import AppletLogo from "@public/images/applet/applet.png";
import { ElTooltip, dayjs } from "element-plus";
import { ComponentInternalInstance, getCurrentInstance, PropType } from "vue";
import { useRoute } from "vue-router";
import "./detail.scss";

export default defineComponent({
	props: {
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	emits: ["change"],
	setup(props, { emit }) {
		const btnList = ref<any[]>([]);
		const readonly = ref(false);
		watch(
			() => props.detail.source,
			() => {
				if (props.detail.source == "develop") {
					useAuthButtons(AuthBtns.appletDevelop).then((res: any) => {
						btnList.value = res.filter((item: any) => item.btnGroup);
						readonly.value = btnList.value.filter((item: any) => item.btnGroup == "1").find((item: any) => item.path == "mod")
							? false
							: true;
					});
				} else {
					readonly.value = true;
				}
			},
			{ deep: true, immediate: true }
		);
		return () => {
			return (
				<div class="p-6 applet-detail-page">
					<Basic detail={props.detail} onChange={() => emit("change")} readonly={readonly.value} />

					<Snapshot detail={props.detail} onChange={() => emit("change")} readonly={readonly.value} />

					<Files detail={props.detail} onChange={() => emit("change")} btns={btnList.value} />
				</div>
			);
		};
	}
});

const Basic = defineComponent({
	props: {
		readonly: Boolean,
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	emits: ["change"],
	setup(props, { emit }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const formEl = ref();
		const formRule = reactive({
			name: [{ required: true, message: "应用名称不能为空", trigger: "change" }]
		});

		const typeList = ref<Dict[]>([]);
		getDictList(DictType.AppletType).then(list => {
			typeList.value = list;
		});
		const changeBasic = () => {
			emit("change");
		};
		watchEffect(() => {});
		return () => {
			return (
				<>
					<div class="p-6 shadow" style="border: 1px solid #eee;">
						<div style="line-height:24px" class="flex justify-between">
							<div>
								<div class="title-left-line"></div>
								<span>{proxy?.$t("applet_basicdetail.tab_title.basic")}</span>
							</div>
							<el-button onClick={changeBasic} type="primary" disabled={props.readonly}>
								{proxy?.$t("common.btn.save")}
							</el-button>
						</div>
						<div class="flex content-center">
							<el-form
								class="pt-4 pl-4 pr-8 grid grid-cols-2 flex-1"
								model={props.detail}
								ref={formEl}
								rules={formRule}
								disabled={props.readonly}
								label-width="100px"
							>
								<el-form-item label={proxy?.$t("applet_basicdetail.tablist_label.name")} prop="key" class="col-span-2">
									<el-radio-group v-model={props.detail.appType} class="ml-4">
										{typeList.value.map((dict: Dict) => {
											return <el-radio label={dict.key}>{dict.label}</el-radio>;
										})}
									</el-radio-group>
								</el-form-item>
								<el-form-item label={proxy?.$t("applet_basicdetail.tablist_label.name")} prop="name">
									<el-input v-model={props.detail.name} placeholder={proxy?.$t("applet_basicdetail.placeholder.name")} />
								</el-form-item>
								<el-form-item label={proxy?.$t("applet_basicdetail.tablist_label.key")} prop="key">
									<el-input
										v-model={props.detail.key}
										placeholder={proxy?.$t("applet_basicdetail.placeholder.key")}
										disabled={!!props.detail.id}
									/>
								</el-form-item>
								<el-form-item label={proxy?.$t("applet_basicdetail.tablist_label.version")} prop="version">
									<el-input v-model={props.detail.version} placeholder={proxy?.$t("applet_basicdetail.placeholder.version")} />
								</el-form-item>
								<el-form-item label={proxy?.$t("applet_basicdetail.tablist_label.home")} prop="home">
									<el-input v-model={props.detail.home} placeholder="http://127.0.0.1:8080/index.html" />
								</el-form-item>
								<el-form-item label={proxy?.$t("applet_basicdetail.tablist_label.desc")} prop="key" class="col-span-2">
									<el-input
										type="textarea"
										v-model={props.detail.desc}
										rows={4}
										placeholder={proxy?.$t("applet_basicdetail.placeholder.desc")}
									/>
								</el-form-item>
							</el-form>
							<div class="w-56 p-4">
								<UploadImg
									disabled={props.readonly}
									showTips={false}
									v-model:imageUrl={props.detail.logo}
									emptyTips={proxy?.$t("applet_basicdetail.uploadimg.emptytips")}
									height="235px"
									width="100%"
									autoUpload
								></UploadImg>
							</div>
						</div>
					</div>
				</>
			);
		};
	}
});
const Snapshot = defineComponent({
	props: {
		readonly: Boolean,
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	emits: ["change"],
	setup(props, { emit }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const imgs = ref<string[]>([]);
		watchEffect(() => {
			imgs.value = props.detail.photo?.split(",").filter((img: string) => (img ? true : false)) || [];
		});

		const changeSnapshot = (res: any, i: number, op: string) => {
			switch (op) {
				case "add":
					imgs.value.push(res.result);
					break;
				case "mod":
					imgs.value.splice(i, 1, res.result);
					break;
				case "del":
					imgs.value.splice(i, 1);
					break;
			}
			props.detail.photo = imgs.value.join(",");
			emit("change");
		};
		return () => {
			return (
				<>
					<div class="p-6 shadow mt-4" style="border: 1px solid #eee;">
						<div style="line-height:24px">
							<div class="title-left-line"></div>
							<span>{proxy?.$t("applet_basicdetail.tab_title.basic")}</span>
						</div>
						<div class="flex content-center">
							<div class="p-4 flex w-full">
								{imgs.value.map((imgPath, i) => (
									<>
										<UploadImg
											disabled={props.readonly}
											showTips={false}
											class="applet-snapshot-image border-2 border-gray-400 w-1/4"
											onSubmit={res => changeSnapshot(res, i, "mod")}
											onCleanImage={() => changeSnapshot(null, i, "del")}
											imageUrl={`${imgs.value[i]}`}
											autoUpload
											emptyTips={proxy?.$t("applet_basicdetail.uploadimg.emptytips")}
											height="100%"
											width="100%"
										/>
										{/* <el-image class="w-full h-full" src={`${filePrefix()}${imgPath}`} /> */}
									</>
								))}
								{imgs.value.length < 4 ? (
									<UploadImg
										disabled={props.readonly}
										showTips={false}
										class="applet-snapshot-image w-1/4"
										onSubmit={res => changeSnapshot(res, imgs.value.length, "add")}
										autoUpload
										emptyTips={proxy?.$t("applet_basicdetail.uploadimg.emptytips")}
										height="100%"
										width="100%"
									/>
								) : null}
							</div>
						</div>
					</div>
				</>
			);
		};
	}
});

import Empty from "@/components/Empty";
import UploadFile from "@/components/Upload/UploadFile.vue";
import { IS_API_PROXY } from "@/config/config";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { PublicStore } from "@/stores/modules/public";
import { formatSize } from "@/utils/format";
import { openWin } from "@/utils/routerUtil";
const Files = defineComponent({
	props: {
		btns: {
			type: Array,
			default() {
				return [];
			}
		},
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	emits: ["change"],
	setup(props, { emit }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const btnList = ref<any[]>([]);
		watchEffect(() => {
			btnList.value = (props.btns || []).filter((item: any) => item.btnGroup == "3");
		});
		const publicStore = PublicStore();
		const state = reactive({
			pageData: {
				dataList: [] as any[],
				page: 1,
				pageSize: 10
			}
		});
		watchEffect(() => {
			state.pageData.dataList = props.detail.resource ? JSON.parse(props.detail.resource) : [];
		});

		// 表格配置项
		const columns: ColumnProps[] = [
			{ prop: "name", label: proxy?.$t("applet_basicdetail.tablist_label.filename") },
			{ prop: "size", label: proxy?.$t("applet_basicdetail.tablist_label.size"), width: 120 },
			{ prop: "type", label: proxy?.$t("applet_basicdetail.tablist_label.filetype") },
			{ prop: "updateTime", label: proxy?.$t("applet_basicdetail.tablist_label.update_time"), width: 180 }
		];
		const uploadFileEl = ref();
		const clickBtn = (fn: string, row: any) => {
			switch (fn) {
				case "del":
					state.pageData.dataList.splice(row.$index, 1);
					break;
			}
			props.detail.resource = JSON.stringify(state.pageData.dataList);
			emit("change");
		};
		const uploadSuccess = (res: any) => {
			state.pageData.dataList.push(res.result);
			props.detail.resource = JSON.stringify(state.pageData.dataList);
			emit("change");
		};
		return () => {
			return (
				<>
					<div class="p-6 shadow mt-4" style="border: 1px solid #eee;">
						<div class="flex items-center justify-between w-full pb-4">
							<div style="line-height:24px">
								<div class="title-left-line"></div>
								<span>{proxy?.$t("applet_basicdetail.tab_title.doc")}</span>
							</div>
							<div class="">
								{btnList.value.find(btn => btn.path == "upload") && (
									<>
										<el-button
											type="primary"
											onClick={() => {
												uploadFileEl.value.selectingFile();
											}}
										>
											{proxy?.$t("applet_basicdetail.btn.upload")}
										</el-button>
										<UploadFile
											showTips={false}
											onSubmitFileInfo={uploadSuccess}
											ref={uploadFileEl}
											style="display: none;"
											headers={{ Authentication: publicStore.token }}
										/>
									</>
								)}
							</div>
						</div>
						<div class="content-center">
							<el-table data={state.pageData.dataList} stripe highlight-current-row>
								{{
									default: () => {
										return (
											<>
												<el-table-column
													align="center"
													type="index"
													width="60"
													index={(i: number) => (state.pageData.page - 1) * state.pageData.pageSize + i + 1}
												/>
												;
												{columns.map((prop: ColumnProps) => {
													return (
														<el-table-column prop={prop.prop} label={prop.label} width={prop.width}>
															{{
																default: (scope: any) => {
																	return prop.prop == "size" ? (
																		formatSize(scope.row[prop.prop]).full
																	) : prop.prop == "name" ? (
																		<el-link
																			type="primary"
																			target="_blank"
																			href={`${filePrefix()}${scope.row[prop.prop as string]}`}
																		>
																			{scope.row[prop.prop as string]}
																		</el-link>
																	) : (
																		scope.row[prop.prop as string] || ""
																	);
																}
															}}
														</el-table-column>
													);
												})}
												<el-table-column
													prop="op"
													fixed="right"
													label={proxy?.$t("applet_basicdetail.tablist_label.operate")}
													width="80"
												>
													{{
														default: (scope: any) => {
															return (
																<>
																	{btnList.value.find((item: any) => item.path == "del") && (
																		<el-link
																			type="danger"
																			link
																			class="iconfont icontrash-2"
																			onClick={() => {
																				clickBtn("del", scope);
																			}}
																		>
																			{proxy?.$t("applet_basicdetail.btn.delete")}
																		</el-link>
																	)}
																</>
															);
														}
													}}
												</el-table-column>
											</>
										);
									},
									empty: () => {
										return (
											<div class="h-60 mt-10">
												<Empty
													showButton={false}
													title={proxy?.$t("applet_basicdetail.empty.title")}
													subtitle={proxy?.$t("applet_basicdetail.empty.subtitle")}
												/>
											</div>
										);
									}
								}}
							</el-table>
						</div>
					</div>
				</>
			);
		};
	}
});

/*eslint-disable @typescript-eslint/no-unused-vars */
const OldInfo = defineComponent({
	props: {
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	emits: ["clickDetailMod"],
	setup(props, { emit }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();
		const publicStore = PublicStore();
		const { gotoAppletPage, gotoAccess } = useApplet();
		return () => {
			return (
				<>
					<div class="p-6 shadow" style="border: 1px solid #eee;">
						<div style="line-height:24px">
							<div class="title-left-line"></div>
							<span>{proxy?.$t("applet_basicdetail.tab_title.basic")}</span>
						</div>
						<div class="flex content-center">
							<div class="p-4 grid grid-cols-2 space-y-2 flex-1">
								<div class="flex  mt-2">
									<div class="w-32">应用名称</div>
									<div class="flex-1">
										<el-link
											type="primary"
											underline={false}
											onClick={() => {
												emit("clickDetailMod");
											}}
										>
											{props.detail.name || "--"}
										</el-link>
									</div>
								</div>
								<div class="flex ">
									<div class="w-32">应用标识</div>
									<div class="flex-1">{props.detail.key}</div>
								</div>
								<div class="flex">
									<div class="w-32">
										访问地址
										<ElTooltip
											raw-content
											v-slots={{
												content: () => {
													return <div class="title">添加并启动了“安装方式”为“资源文件”的服务，即可通过“访问地址”访问</div>;
												}
											}}
										>
											<i class="iconfont iconhelp-circle pl-2 "></i>
										</ElTooltip>
									</div>
									<div class="flex-1">
										{!IS_API_PROXY ? (
											<el-link type="primary" underline={false} onClick={() => gotoAccess(props.detail)}>
												{`http://${route.query.key}.${window.location.host}`}
											</el-link>
										) : (
											<el-link
												type="primary"
												underline={false}
												onClick={() => {
													openWin(`/${props.detail.subdomain}/#/?token=${publicStore.token}`);
												}}
											>
												{`/${props.detail.subdomain}/#/?token=${publicStore.token}`}
											</el-link>
											// <span class="text-gray-400">使用域名访问平台时生成</span>
										)}
									</div>
								</div>
								<div class="flex">
									<div class="w-32">
										实际地址
										<ElTooltip
											raw-content
											v-slots={{
												content: () => {
													return (
														<div class="title">
															系统将通过“访问地址”代理到“实际地址”，但如果设置了“资源文件”服务，系统优先访问“资源文件”。
														</div>
													);
												}
											}}
										>
											<i class="iconfont iconhelp-circle pl-2 "></i>
										</ElTooltip>
									</div>
									<div class="flex-1">
										<el-link type="primary" underline={false} onClick={() => gotoAppletPage(props.detail)}>
											{props.detail.home || "--"}
										</el-link>
									</div>
								</div>
								<div class="flex ">
									<div class="w-32">创建时间</div>
									<div class="flex-1">
										{(props.detail.createTime && dayjs(props.detail.createTime).format("YYYY-MM-DD hh:mm:ss")) || "--"}
									</div>
								</div>
								<div class="flex ">
									<div class="w-32">修改时间</div>
									<div class="flex-1">
										{(props.detail.updateTime && dayjs(props.detail.updateTime).format("YYYY-MM-DD hh:mm:ss")) || "--"}
									</div>
								</div>
								<div class="flex ">
									<div class="w-32">应用更新时间</div>
									<div class="flex-1">
										{(props.detail.svcUpdateTime && dayjs(props.detail.svcUpdateTime).format("YYYY-MM-DD hh:mm:ss")) || "--"}
									</div>
								</div>
								<div class="flex ">
									<div class="w-32">创建人</div>
									<div class="flex-1">{props.detail.creator || "--"}</div>
								</div>
								<div class="flex col-span-2">
									<div class="w-32">描述</div>
									<div class="flex-1">{props.detail.desc || "--"}</div>
								</div>
							</div>
							<el-image style="width:200px;" src={props.detail.logo || AppletLogo} fit="contain"></el-image>
						</div>
					</div>
					<div class="p-6 shadow mt-6" style="border: 1px solid #eee;">
						<div style="line-height:24px">
							<div class="title-left-line"></div>
							<span>文档信息</span>
						</div>
						<div class="p-4 grid grid-cols-1">
							<div class="flex ">
								<div class="w-32">应用文档</div>
								<div class="flex-1">
									<el-link href={props.detail.doc} type="primary" underline={false} target="_blank">
										{props.detail.doc || "--"}
									</el-link>
								</div>
							</div>
						</div>
					</div>
				</>
			);
		};
	}
});
